package com.xzz.web.controller;

import com.xzz.domain.PayOrder;
import com.xzz.dto.AlipayNotifyDto;
import com.xzz.dto.ApplyPayDto;
import com.xzz.result.JSONResult;
import com.xzz.service.IPayOrderService;
import com.xzz.service.IPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private IPayService payService;

    /**
     * 检查支付单是否已经存在
     * @param orderNo
     */
    @RequestMapping(value="/checkPayOrder/{orderNo}",method= RequestMethod.GET)
    public JSONResult saveOrUpdate(@PathVariable("orderNo") String orderNo){
        PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
        return payOrder != null ? JSONResult.success() : JSONResult.error();
    }

    /**
     * 发起支付申请
     * @param dto
     */
    @RequestMapping(value="/apply",method= RequestMethod.POST)
    public JSONResult apply(@RequestBody ApplyPayDto dto){
        String payResponse = payService.apply(dto);
        return JSONResult.success(payResponse);
    }

    /**
     * 支付宝的异步回调通知接口
     * @param dto
     */
    @RequestMapping(value="/alipay/notify")
    public String notify(AlipayNotifyDto dto){
        try {
            return payService.notify(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return "error";//不是返回success，支付宝会最大努力通知
        }
    }
}
